package com.example.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.backend.entity.CaiPin;
import com.example.backend.entity.ShangJia;
import com.example.backend.entity.vo.ShowSjInfo;
import com.example.backend.entity.vo.YHView;
import com.example.backend.mapper.CaiPinMapper;
import com.example.backend.mapper.ShangJiaMapper;
import com.example.backend.service.IYHViewService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class YHViewService implements IYHViewService {

    @Resource
    private ShangJiaMapper shangJiaMapper;
    @Resource
    private CaiPinMapper caiPinMapper;

    @Override
    public List<YHView> queryYHViewList(String keyword, Integer limit) {
        List<YHView> yhViewList = new ArrayList<>();
        LambdaQueryWrapper<ShangJia> wrapper = new LambdaQueryWrapper<>();
        if (!keyword.equals("全部")) {
            wrapper.like(ShangJia::getName, keyword);
        }
        List<ShangJia> shangJias = shangJiaMapper.selectList(wrapper);
        List<Integer> shangJiaIdList = shangJias.stream()
                .limit(limit)
                .map(ShangJia::getSjid)
                .toList();
        if (shangJiaIdList.isEmpty()) {
            return null;
        }
        for (Integer shangJiaId : shangJiaIdList) {
            YHView yhView = new YHView();
            ShowSjInfo showSjInfo = new ShowSjInfo();
            ShangJia shangJia = shangJiaMapper.selectById(shangJiaId);
            showSjInfo.setSjid(shangJiaId);
            showSjInfo.setYhid(shangJia.getYhid());
            showSjInfo.setName(shangJia.getName());
            showSjInfo.setQsf(Double.valueOf(shangJia.getQsf()));
            showSjInfo.setPsf(Double.valueOf(shangJia.getPsf()));
            showSjInfo.setAddress(shangJia.getAddress());
            showSjInfo.setStatus(shangJia.getStatus());
            showSjInfo.setSjtp(shangJia.getSjtp());
            yhView.setSjInfo(showSjInfo);
            List<CaiPin> caiPinList = caiPinMapper.queryCaiPinBySjid(shangJiaId);
            yhView.setCpList(caiPinList);
            yhViewList.add(yhView);
        }
        return yhViewList;
    }
}
